layui.use(['table', 'admin', 'ax', 'laydate', 'layer'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;
    var layer = layui.layer;
    var element = layui.element;

    // 不再依赖被注释掉的Feng变量
    layui.extend({
        wangEditor: './wangEditor' // {/}的意思即代表采用自有路径，即不跟随 base 路径
    })

    /**
     * 实施问题知识库管理
     */
    var KnowledgeBase = { tableId: "knowledgeBaseTable" };

    /**
     * 初始化表格的列
     */
    KnowledgeBase.initColumn = function () {
        return [[
            { type: 'checkbox', fixed: 'left' },
            { field: 'id', title: 'ID', width: 80, fixed: 'left' },
            { field: 'title', title: '标题', minWidth: 200 },
            { field: 'createTime', title: '创建时间', width: 180 },
            { field: 'updateTime', title: '更新时间', width: 180 },
            { fixed: 'right', title: '操作', toolbar: '#tableBar', width: 200 }
        ]];
    };

    /**
     * 显示详情
     */
    KnowledgeBase.showDetail = function (data) {
        // 调用后端接口获取完整详情
        var loading = layer.load(1, { shade: [0.1, '#fff'] });

        $.ajax({
            url: '/knowledgeBase/detail',
            type: 'get',
            data: { id: data.id },
            success: function (res) {
                layer.close(loading);
                if (res.code === 0 || res.success === true) {
                    var knowledgeBase = res.data;

                    // 创建美化后的详情弹窗内容
                    var detailHtml = `
                <div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
                    <div style="background-color: #1e9fff; color: white; padding: 15px 20px; font-size: 18px; font-weight: 500; border-radius: 8px 8px 0 0;">
                        知识库详情
                    </div>
                    <div style="background-color: white; padding: 25px; border-radius: 0 0 8px 8px;">
                        <div style="margin-bottom: 20px;">
                            <div style="font-weight: 500; color: #666; margin-bottom: 8px;">标题</div>
                            <div style="font-size: 18px; font-weight: 500; color: #1e9fff;">${knowledgeBase.title}</div>
                        </div>
                        
                        <div style="margin-bottom: 20px;">
                            <div style="font-weight: 500; color: #666; margin-bottom: 8px;">内容</div>
                            <div style="border: 1px solid #e6e6e6; border-radius: 4px; padding: 20px; min-height: 200px; background-color: #fafafa; line-height: 1.8;">
                                ${knowledgeBase.content}
                            </div>
                        </div>
                        
                        <div style="color: #999; font-size: 14px; padding-top: 15px; border-top: 1px solid #f0f0f0;">
                            <div style="margin-bottom: 8px;">创建时间: ${knowledgeBase.createTime}</div>
                            <div>更新时间: ${knowledgeBase.updateTime || knowledgeBase.createTime}</div>
                        </div>
                    </div>
                </div>
                `;

                    // 创建隐藏的详情div
                    var detailDivId = 'knowledgeBaseDetailDiv';
                    if (!$('#' + detailDivId).length) {
                        var div = $('<div>').attr('id', detailDivId).css('display', 'none');
                        $(document.body).append(div);
                    }
                    $('#' + detailDivId).html(detailHtml);

                    // 打开弹窗
                    layer.open({
                        title: false,
                        type: 1,
                        content: $('#' + detailDivId),
                        area: ['900px', '650px'],
                        btn: ['关闭'],
                        btn1: function (index) {
                            layer.close(index);
                        },
                        success: function () {
                            // 弹窗打开后的回调，可以添加动画效果
                            $('#' + detailDivId).find('.layui-card').css('opacity', 0).animate({ opacity: 1 }, 300);
                        }
                    });
                } else {
                    layer.msg('获取详情失败: ' + (res.message || '未知错误'));
                }
            },
            error: function () {
                layer.close(loading);
                layer.msg('网络错误，请稍后重试');
            }
        });
    };

    /**
     * 点击查询按钮
     */
    KnowledgeBase.search = function () {
        var queryData = {};
        queryData['title'] = $("#title").val();
        table.reload(KnowledgeBase.tableId, {
            where: queryData, page: { curr: 1 }
        });
    };

    /**
     * 弹出添加对话框
     */
    KnowledgeBase.openAddDlg = function () {
        window.location.href = '/knowledgeBase/addPage';
    };

    /**
   * 点击编辑
   */
    KnowledgeBase.openEditDlg = function (data) {
        var loading = layer.load(1, { shade: [0.1, '#fff'] });

        // 先获取完整数据
        $.ajax({
            url: '/knowledgeBase/detail',
            type: 'get',
            data: { id: data.id },
            success: function (res) {
                layer.close(loading);
                if (res.code === 0 || res.success === true) {
                    var knowledgeBase = res.data;
                    console.log('获取到的知识库数据:', knowledgeBase); // 添加调试信息

                    // 创建编辑表单
                    var editDivId = 'editKnowledgeBaseDiv';
                    if (!$('#' + editDivId).length) {
                        var editHtml = `
                    <div id="${editDivId}" style="display: none;">
                        <form class="layui-form" id="editKnowledgeBaseForm">
                            <input type="hidden" name="id" id="editId">
                            <div class="layui-form-item">
                                <label class="layui-form-label">标题</label>
                                <div class="layui-input-block">
                                    <input type="text" name="title" id="editTitle" lay-verify="required" placeholder="请输入标题" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">内容</label>
                                <div class="layui-input-block">
                                    <textarea class="layui-textarea" id="editContent" style="display: none;">${knowledgeBase.content || ''}</textarea>
                                </div>
                            </div>
                            <div class="layui-form-item layui-hide">
                                <button class="layui-btn" lay-submit lay-filter="editSubmit">提交</button>
                            </div>
                        </form>
                    </div>`;
                        $(document.body).append(editHtml);
                    } else {
                        // 如果表单已存在，直接设置textarea的值
                        $('#editContent').val(knowledgeBase.content || '');
                    }

                    // 填充数据
                    $('#editId').val(knowledgeBase.id);
                    $('#editTitle').val(knowledgeBase.title);

                    // 保存knowledgeBase到全局，避免作用域问题
                    window.currentKnowledgeBase = knowledgeBase;

                    // 打开弹窗
                    layer.open({
                        title: '编辑知识库',
                        type: 1,
                        content: $('#' + editDivId),
                        area: ['900px', '600px'],
                        btn: ['保存', '取消'],
                        btn1: function (index) {
                            // 触发表单提交
                            $('#editKnowledgeBaseForm').find('button[lay-submit]').click();
                        },
                        btn2: function (index) {
                            layer.close(index);
                        },
                        success: function () {
                            // 使用LayUI的layedit模块初始化富文本编辑器
                            layui.use(['layedit'], function () {
                                var layedit = layui.layedit;

                                // 构建富文本编辑器
                                var contentEditor = layedit.build('editContent', {
                                    tool: ['strong', 'italic', 'underline', 'del', '|', 'fontFomatt', 'face', 'image', '|',
                                        'left', 'center', 'right', '|', 'link', 'unlink', '|', 'code', 'preview']
                                    , height: 400
                                });

                                // 存储编辑器实例到全局
                                window.editContentEditor = contentEditor;

                                // 使用更可靠的方式设置内容，增加延迟时间
                                setTimeout(function () {
                                    try {
                                        // 尝试获取编辑器iframe
                                        var iframes = document.getElementsByTagName('iframe');
                                        var editorIframe = null;

                                        // 查找正确的iframe（包含layedit-iframe类的）
                                        for (var i = 0; i < iframes.length; i++) {
                                            if (iframes[i].className.indexOf('layedit-iframe') !== -1) {
                                                editorIframe = iframes[i];
                                                break;
                                            }
                                        }

                                        // 如果找到了iframe且有内容需要设置
                                        if (editorIframe && window.currentKnowledgeBase && window.currentKnowledgeBase.content) {
                                            var iframeDoc = editorIframe.contentDocument || editorIframe.contentWindow.document;
                                            var iframeBody = iframeDoc.body;

                                            if (iframeBody) {
                                                iframeBody.innerHTML = window.currentKnowledgeBase.content;
                                                console.log('成功设置编辑器内容');
                                            } else {
                                                console.error('未找到iframe body元素');
                                            }
                                        } else {
                                            console.warn('未找到编辑器iframe或内容为空');
                                        }
                                    } catch (e) {
                                        console.error('设置编辑器内容时出错:', e);
                                    }
                                }, 300); // 增加延迟时间到300毫秒
                            });
                        }
                    });
                } else {
                    layer.msg('获取详情失败: ' + (res.message || '未知错误'));
                }
            },
            error: function () {
                layer.close(loading);
                layer.msg('网络错误，请稍后重试');
            }
        });
    };

    /**
     * 点击删除
     */
    KnowledgeBase.onDeleteItem = function (data) {
        layer.confirm('确定要删除这条知识库记录吗？', {
            btn: ['确定', '取消']
        }, function (index) {
            // 显示加载状态
            var loading = layer.load(1, { shade: [0.1, '#fff'] });

            $.ajax({
                url: '/knowledgeBase/delete',
                type: 'post',
                data: { id: data.id },
                success: function (res) {
                    layer.close(loading);
                    if (res.code === 0 || res.success === true) {
                        layer.msg('删除成功');
                        // 刷新表格
                        table.reload(KnowledgeBase.tableId);
                    } else {
                        layer.msg('删除失败: ' + (res.message || '未知错误'));
                    }
                },
                error: function () {
                    layer.close(loading);
                    layer.msg('网络错误，请稍后重试');
                }
            });

            layer.close(index);
        });
    };

    // 页面加载完成后初始化
    $(function () {
        // 渲染表格
        var tableResult = table.render({
            elem: '#' + KnowledgeBase.tableId,
            url: '/knowledgeBase/list',
            page: true,
            height: "full-98",
            cellMinWidth: 100,
            cols: KnowledgeBase.initColumn()
        });

        // 搜索按钮点击事件
        $('#btnSearch').click(function () {
            KnowledgeBase.search();
        });

        // 添加按钮点击事件
        $('#btnAdd').click(function () {
            KnowledgeBase.openAddDlg();
        });

        // 工具条点击事件
        table.on('tool(' + KnowledgeBase.tableId + ')', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'detail') {
                // 处理详情按钮点击
                KnowledgeBase.showDetail(data);
            } else if (layEvent === 'edit') {
                // 处理编辑按钮点击
                KnowledgeBase.openEditDlg(data);
            } else if (layEvent === 'delete') {
                // 处理删除按钮点击
                KnowledgeBase.onDeleteItem(data);
            }
        });

        // 编辑表单提交
        layui.form.on('submit(editSubmit)', function (data) {
            // 获取富文本内容 - 使用layedit模块
            var editorContent = '';
            if (window.editContentEditor) {
                try {
                    editorContent = layui.layedit.getContent(window.editContentEditor);
                } catch (e) {
                    console.error('获取编辑器内容失败:', e);
                    // 如果获取失败，尝试直接从textarea获取
                    editorContent = $('#editContent').val();
                }
            } else {
                // 如果编辑器不存在，尝试直接获取内容
                editorContent = $('#editContent').val();
            }
            data.field.content = editorContent;

            // 显示加载状态
            var loading = layer.load(1, { shade: [0.1, '#fff'] });

            $.ajax({
                url: '/knowledgeBase/edit1',
                type: 'post',
                data: data.field,
                success: function (res) {
                    layer.close(loading);
                    if (res.code === 0 || res.success === true) {
                        layer.msg('编辑成功！', { icon: 1 ,time: 500}, function () {
                            // 关闭弹窗
                            layer.closeAll();
                            // 刷新表格
                            table.reload(KnowledgeBase.tableId);
                            // 清理编辑器实例
                            window.editContentEditor = null;
                        });
                    } else {
                        layer.msg('编辑失败: ' + (res.message || '未知错误'));
                    }
                },
                error: function () {
                    layer.close(loading);
                    layer.msg('网络错误，请稍后重试');
                }
            });
            return false;
        });
    });
});